
import { createStore, mapState, useStore, ActionContext } from 'vuex';
import { computed } from "vue";
import persistedState from "vuex-persistedstate";
import { Response } from "../type.d";
import { create, all } from "mathjs";

export const math = create(all, {
  epsilon: 1e-12,
  matrix: "Matrix",
  number: "BigNumber", // 可选值：number BigNumber
  precision: 64,
  predictable: false,
  randomSeed: null
});

export interface State {
  theme: "light" | "dark";
  userInfo: AnyObject;
  items: AnyObject[];
  itemIndex: number;
  liveTradeData: AnyObject[];
  liveTask: number | NodeJS.Timer;
  getMarketTask: number | NodeJS.Timer;
};

const state: State = {
  theme: "light",
  userInfo: {},
  items: [{ projectName: "暂未添加项目" }],
  itemIndex: 0,
  liveTradeData: [],
  liveTask: 0,
  getMarketTask: 0
};

const mutations = {
  setState(state: State, { key, value }: { key: keyof State; value: any }) {
    (<State>state[key]) = value;
  },
};

const actions = {
  getItems({ commit, state }: ActionContext<State, any>) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: "/project/list",
        success: <any>(({ data }: Response) => {
          commit("setState", { key: "items", value: data });
          resolve(data);
        }),
        fail(result) {
          reject(result);
        },
      });
    })
  },
  getLiveTrade({ commit, state }: ActionContext<State, any>) {
    state.liveTask && clearInterval(state.liveTask);
    const requestData = () => {
      uni.request({
        url: "/exchange/trades",
        data: { projectId: state.items[state.itemIndex].id },
        method: "POST",
        success({ data }: any) {
          commit("setState", { key: "liveTradeData", value: data });
        }
      });
      return requestData;
    }
    state.liveTask = setInterval(requestData(), 3000);
  }
};

export const useMapState = (getKeys: string[]) => {
  const $store = useStore();
  const storeState: any = {};
  const storeFns = mapState(getKeys)

  Object.keys(storeFns).forEach((fnKeys: string) => {
    const fn = storeFns[fnKeys].bind({ $store })
    storeState[fnKeys] = computed(fn)
  })

  return storeState;
}

export default createStore({
  plugins: [
    persistedState({
      storage: {
        getItem: key => uni.getStorageSync(key)?.value,
        setItem: (key, value) => uni.setStorageSync(key, { key, createTime: Date.now(), value }),
        removeItem: key => uni.removeStorageSync(key)
      },
      reducer(val) {
        return {
          userInfo: val.userInfo,
          theme: val.theme,
          items: val.items,
          itemIndex: val.itemIndex
        }
      }
    })
  ],
  modules: {},
  state,
  mutations,
  actions
});